package com.qys.livesMall.finance.service.impl;

import com.qys.livesMall.cache.utils.CacheUtils;
import com.qys.livesMall.finance.enums.FinanceMessageEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.qys.livesMall.finance.common.FinanceLockPrefix.SHOP_ACCOUNT_LOCK;

/**
 * @menu AccountBaseServer
 * @date 2023/11/09 9:39
 */
@Slf4j
@Service
public class AccountBaseServer {

    @Autowired
    private CacheUtils cacheUtils;

    protected boolean getLock(String lockPrefix,Object unique){
        String key=lockPrefix+unique.toString();
        boolean lock=cacheUtils.getLock(key, CacheUtils.LOCK_WAIT_TIME_5_SECONDS);
        long outTime=System.currentTimeMillis()+3000;
        //防止系统时间回拨
        int count=0;
        while (!lock) {
            lock = getLock(key, CacheUtils.LOCK_WAIT_TIME_5_SECONDS);
            if (System.currentTimeMillis()>=outTime||count>=100){
                return false;
            }
            try {
                TimeUnit.MILLISECONDS.sleep(50);
                count++;
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
        //获得锁
        return true;
    }

    //释放锁
    protected void releaseLock(String lockPrefix,Object unique){
        try {
            String key = lockPrefix + unique.toString();
            cacheUtils.releaseLock(key);
        }catch (Exception e){
            log.error("释放锁异常："+e);
        }
    }


}

